//
//  ZZptrwPDController.m
//  pacc
//
//  Created by 测试 on 2018/6/4.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "ZZptrwPDController.h"
#import "SlideBarCell.h"
#import "searchController.h"
#import "pingtairenwuModel.h"
#import "ZZcommonModel.h"
#import "orderModel.h"
#import "taskDetailsCVc.h"
#import "ZXPickerView.h"
#import "ptrwPdCell.h"
#import "ptrwCell.h"
#import "pingtairenwuModel.h"
#import "yuepianController.h"
#define TOPHEIGHT 45

@interface ZZptrwPDController ()<UIPickerViewDelegate,UIPickerViewDataSource,myPickerViewDelegate,UITableViewDelegate,UITableViewDataSource,UIPickerViewDataSource,UIPickerViewDelegate>
//tableview
@property (strong, nonatomic)  UITableView *myTableView1;
@property (strong, nonatomic)  UITableView *myTableView2;

//TableViews的数据源
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (strong, nonatomic) NSMutableArray *dataSource1;
@property (strong, nonatomic) NSMutableArray *dataSource2;
@property (strong, nonatomic) NSMutableArray *temdataSource;
@property (strong, nonatomic) NSMutableArray *dataSource4;
@property (strong, nonatomic) NSMutableArray *docdataSource;
//医生列表
@property (nonatomic,strong)UIPickerView * pickerView;//自定义pickerview
@property (nonatomic,strong)NSArray * letter;//保存要展示的字母
@property (nonatomic,strong)NSArray * number;
@property (nonatomic, strong) UIView *maskLayer;
@property (nonatomic, strong) UIButton *tenBtn;
@property (nonatomic, strong) UILabel *tenLabel;
@property (nonatomic, assign) NSInteger temRow;
@property (nonatomic, assign) NSString* sum;

@property (strong, nonatomic) NSMutableArray *docArr;
@property (strong, nonatomic) NSMutableArray *temArr;


@property (strong, nonatomic) NSFetchedResultsController *fetchedResultController;

@property (copy, nonatomic) NSString *nameStr;
@property (assign) NSInteger tabCount;
@property (strong, nonatomic) NSMutableArray *btnNameArr;
@property (nonatomic ,strong) ZXPickerView * zxpickerView1;
@property (strong, nonatomic) NSString *temnamestr;
@property (strong, nonatomic) UIView *sureview;

@property (assign) int pageNo1;
@property (assign) int pageNo2;

///@brife 整个视图的大小
@property (assign) CGRect mViewFrame;

///@brife 下方的ScrollView
@property (strong, nonatomic) UIScrollView *scrollView;

///@brife 上方的按钮数组
@property (strong, nonatomic) NSMutableArray *topViews;

///@brife 下方的表格数组
@property (strong, nonatomic) NSMutableArray *scrollTableViews;


///@brife 当前选中页数
@property (assign) NSInteger currentPage;

///@brife 下面滑动的View
@property (strong, nonatomic) UIView *slideView;

///@brife 上方的view
@property (strong, nonatomic) UIView *topMainView;

///@brife 上方的ScrollView
@property (strong, nonatomic) UIScrollView *topScrollView;

@end

@implementation ZZptrwPDController
@synthesize maskLayer;
- (void)action_removeMask{
    // 移除全屏点击事件
    [maskLayer removeFromSuperview];
}
- (void)addMaskLayer{
    
    // 添加遮罩
    maskLayer = [UIView  new];
    [maskLayer setFrame:[[UIScreen mainScreen] bounds]];
    [maskLayer setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
    [self.view addSubview:maskLayer];
}


#pragma mark -- talbeView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataSource.count;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentPage) {
        return 130;
    }else  return 125;
}

-(UITableViewCell *)tableView:tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!_currentPage) {
        BOOL nibsRegistered=NO;
        if (!nibsRegistered) {
            UINib *nib=[UINib nibWithNibName:@"ptrwCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:@"ptrwcell"];
            nibsRegistered=YES;
        }
        ptrwCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ptrwcell"];
        cell.arrData = _dataSource[indexPath.row];
        [cell.qiangdanBtn addTarget:self action:@selector(qiangdan:) forControlEvents:UIControlEventTouchUpInside];
        [cell.qiangdanBtn setTitle:cell.zid forState:UIControlStateHighlighted];
        [cell.qiangdanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [cell.yuepianBtn setTitle:cell.pacUrl forState:UIControlStateHighlighted];
        [cell.yuepianBtn addTarget:self action:@selector(yuepian:) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];
        BOOL nibsRegistered=NO;
        if (!nibsRegistered) {
            UINib *nib=[UINib nibWithNibName:@"ptrwPdCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
            nibsRegistered=YES;
        }
        ptrwPdCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.arrData = _dataSource[indexPath.row];
        [cell.paidanBtn addTarget:self action:@selector(paidan:) forControlEvents:UIControlEventTouchUpInside];
        [cell.detailBtn addTarget:self action:@selector(chakangongdan:) forControlEvents:UIControlEventTouchUpInside];
        [cell.detailBtn setTitle:cell.zid forState:UIControlStateHighlighted];
        [cell.detailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.paidanBtn setTitle:cell.doctorid2 forState:UIControlStateHighlighted];
        [cell.paidanBtn setTitle:cell.zid forState:UIControlStateSelected];
        
        [cell.yuepianBtn setTitle:cell.pacUrl forState:UIControlStateHighlighted];
        [cell.yuepianBtn addTarget:self action:@selector(yuepian:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentPage) {
        if (!my_AppDelegate.assignO) {
            return;
        }
        [self addMaskLayer];
        [self getDoctorList];
        _temRow = indexPath.row;
        self.pickerView.hidden = NO;
        self.sureview.hidden = NO;
        [self.view bringSubviewToFront:self.pickerView];
        [self.view bringSubviewToFront:self.sureview];
        long index =  [self.pickerView selectedRowInComponent:0];
        [self pickerView:self.pickerView didSelectRow:index inComponent:0];
        self.tabBarController.tabBar.hidden = YES;
    }else{
        if (!my_AppDelegate.grabO) {
            return;
        }
        SlideBarCell * cell =[tableView cellForRowAtIndexPath:indexPath];
        taskDetailsCVc *vc= [taskDetailsCVc new];
        vc.odrStatus = @"未派单";
        vc.type = 9;
        vc.zid = cell.zid;
        [self.navigationController pushViewController:vc animated:YES];
    }
   
}

#pragma mark UIPickerView DataSource Method 数据源方法

//指定pickerview有几个表盘
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//指定每个表盘上有几行数据
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSInteger result = 0;
    result = self.letter.count;
    return result;
}

#pragma mark UIPickerView Delegate Method 代理方法

//指定每行如何展示数据（此处和tableview类似）
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString * title = nil;
    title = self.letter[row];
    return title;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"selected == %@",self.letter[row]);
    [_temArr[_temRow] setValue:self.letter[row] forKey:@"doctorName2"];
    [_temArr[_temRow] setValue:self.number[row] forKey:@"doctorid2"];
    _dataSource = [pingtairenwuModel modelSformDics:_temArr];
    [_myTableView2 reloadData];
}
#pragma mark --查看工单 阅片 派单 抢单--
-(void)chakangongdan:(UIButton*)sender{
    NSString * str = [sender titleForState:UIControlStateHighlighted];
    taskDetailsCVc *vc =[taskDetailsCVc new];
    vc.zid = str;
    vc.type = 9;
    vc.isHidden = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)paidan:(UIButton*)sender{
    
    NSString * str = [sender titleForState:UIControlStateHighlighted];
    NSString * str2 = [sender titleForState:UIControlStateSelected];
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    [dic setValue:str forKey:@"doctorId"];
    [dic setValue:str2 forKey:@"orderId"];
    if (!str.length||[str isEqualToString:@"(null)"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择医生"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }else{
    }
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    [NetWorking startPOSTRequestWithUrl:@"orderchooseDoctor" parameters:dic logMes:@"派单" show:YES success:^(NSDictionary *data) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadData];
        });
    } failure:^(NSError *error) {
        
    }];
    NSLog(@"派单 = %@\n%@",str,str2);
}

-(void)qiangdan:(UIButton*)sender{
    if (!my_AppDelegate.grabO) {
        return;
    }
    NSString *title = [sender titleForState:UIControlStateHighlighted];
    NSLog(@"sender.titleLabel.text=%@",title);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否抢单"message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"order/chooseDoctor");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"抢单" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSMutableDictionary *dic =[NSMutableDictionary dictionary];
        NSString *str =[NSString stringWithFormat:@"orderacceptOrder"];
        NSString *nameStr =@"抢单";
        [dic setValue:title forKey:@"orderId"];
        [dic setValue:my_AppDelegate.token forKey:@"token"];
        
        [NetWorking startPOSTRequestWithUrl:str parameters:dic logMes:nameStr show:YES success:^(NSDictionary *data) {
            NSString *msg = [data objectForKey:@"msg"];
            NSString *status = [NSString stringWithFormat:@"%@", [data objectForKey:@"status"]];
            if ([status isEqualToString:@"200"]) {
                [SVProgressHUD showSuccessWithStatus:msg];
                [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self loadData];
                    [SVProgressHUD dismiss];
                });
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            });
        } failure:^(NSError *error) {
            
        }];
        NSLog(@"Cancel Action");
    }];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
-(void)yuepian:(UIButton*)sender{
    if (!my_AppDelegate.grabO) {
        return;
    }
    yuepianController *vc = [yuepianController new];
    NSString * zid = [sender titleForState:UIControlStateHighlighted];
    vc.yuepianURL = zid;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark----加载view数据-----
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNo1 =_pageNo2  = 1;
    _btnNameArr = [NSMutableArray arrayWithObjects:@"抢单",@"派单",nil];
    _scrollTableViews = [[NSMutableArray alloc] init];
    _tabCount = _btnNameArr.count;
    _mViewFrame = self.view.frame;
    if (!_topViews) {
        _topViews =[[NSMutableArray alloc]init];
    }
    [self.view addSubview:self.zxpickerView1];
    [self initScrollView];
    
    [self initTopTabs];
    
    [self initDownTables];
    
    [self loadData];
    
    [self refersh];
    [self creatNavRightBtn];
    
    [self initSlideView];
    
    [self changeBackColorWithPage:0];
    [self creatPickView];
    
   
}
-(void)viewDidAppear:(BOOL)animated{
    
}
-(void)viewWillAppear:(BOOL)animated{
    if (my_AppDelegate.fromMessage) {
        
        UIButton * button = [[UIButton alloc]init];
        button.tag = 1;
        _currentPage = 1;
        [self tabButton:button];
        
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [_myTableView1.mj_header endRefreshing];
    [_myTableView2.mj_header endRefreshing];
    [_myTableView1.mj_footer endRefreshing];
    [_myTableView2.mj_footer endRefreshing];
    my_AppDelegate.fromMessage = NO;
}
-(void)creatPickView{
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, ScreenHeight-216-48, self.view.bounds.size.width, 216)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.backgroundColor = baseBackgroundColor;
    [self.view addSubview:self.pickerView];
    self.pickerView.hidden = YES;
    
    
    self.sureview = [[UIView alloc]initWithFrame:CGRectMake(0, self.pickerView.y-50, ScreenWidth, 50)];
    self.sureview.backgroundColor = [UIColor whiteColor];
    self.sureview.hidden = self.pickerView.hidden;
    [self.view addSubview:self.sureview];
    
    UIButton *sureBtn =[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-50-ZTbigmargin,0 , 50, 50)];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchDown];
    [self.sureview addSubview:sureBtn];
    
    UIButton *cancelBtn =[[UIButton alloc]initWithFrame:CGRectMake(ZTbigmargin,0 , 50, 50)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchDown];
    [self.sureview addSubview:cancelBtn];
}
#pragma mark --pickview点击事件---
-(void)sureClick{
    self.pickerView.hidden = YES;
    self.pickerView.hidden = YES;
    self.sureview.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    [self action_removeMask];
}
-(void)cancelClick{
    [_temArr[_temRow] setValue:@"请选择医生" forKey:@"doctorName2"];
    [_temArr[_temRow] setValue:@"" forKey:@"doctorid2"];
    _dataSource = [pingtairenwuModel modelSformDics:_temArr];
    self.pickerView.hidden = YES;
    self.sureview.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    [self action_removeMask];
    [_myTableView2 reloadData];
}
#pragma mark --加载网络数据--
-(void)getDoctorList{
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    NSMutableArray * arrtem = [[NSMutableArray alloc]init];
    NSMutableArray * arrtem2 = [[NSMutableArray alloc]init];
    my_AppDelegate.docdataSource= [[NSMutableArray alloc]init];
    [NetWorking startPOSTRequestWithUrl:@"doctorlist" parameters:dic logMes:@"医生列表" show:NO success:^(NSDictionary *data) {
        NSArray * arr = [data objectForKey:@"data"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (arr&&![arr isEqual:[NSNull null]]) {
                for (NSDictionary * dicc in arr) {
                    NSString * namestr = [NSString stringWithFormat:@"%@",[dicc objectForKey:@"name"]];
                    NSString * strid = [NSString stringWithFormat:@"%@",[dicc objectForKey:@"userId"]];
                    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                    [dic setValue:namestr forKey:@"namestr"];
                    [dic setValue:strid forKey:@"strid"];
                    [arrtem addObject:namestr];
                    [arrtem2 addObject:strid];
                }
                self.letter = [arrtem mutableCopy];
                self.number = [arrtem2 mutableCopy];
                [self.pickerView reloadAllComponents];
            }
        });
        NSLog(@"my_AppDelegate.docdataSource-=-%@",my_AppDelegate.docdataSource);
    } failure:^(NSError *error) {
        
    }];
}

-(void)loadData{
    [self getDoctorList];
    self.myTableView1.mj_footer.hidden = NO;
    self.myTableView2.mj_footer.hidden = NO;
    _pageNo1 = _pageNo2 = 1;
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    if (!_dataSource1) {
        _dataSource1 =[[NSMutableArray alloc]init];
    }
    if (!_dataSource2) {
        _dataSource2 =[[NSMutableArray alloc]init];
    } if (!_temdataSource) {
        _temdataSource =[[NSMutableArray alloc]init];
    }if (!_temArr) {
        _temArr =[[NSMutableArray alloc]init];
    }
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    NSString *str =[NSString stringWithFormat:@"ordergetNotAcceptOrder"];
    _nameStr =@"平台任务";
    [dic setValue:@10 forKey:@"size"];
    [dic setValue:@1 forKey:@"page"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    [_dataSource removeAllObjects];
    int tabviewTag = _currentPage % 2;
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    [reuseTableView reloadData];
    self.myTableView1.scrollEnabled = NO;
    self.myTableView2.scrollEnabled = NO;
    [NetWorking startPOSTRequestWithUrl:str parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            NSArray *arr = [data objectForKey:@"data"];
            self->_sum = [data objectForKey:@"sum"];
            if (self->_sum.integerValue<10) {
                self.myTableView1.mj_footer.hidden = YES;
                self.myTableView2.mj_footer.hidden = YES;
            }
            self->_temArr = [arr mutableCopy];
            switch (self->_currentPage) {
                case 0:
                    //已接单
                    self->_dataSource1 = [pingtairenwuModel modelSformDics:arr];
                    self->_dataSource = [self->_dataSource1 mutableCopy];
                    
                    break;
                case 1:
                    //已接单
                    self->_dataSource2 = [pingtairenwuModel modelSformDics:self->_temArr];
                    self->_dataSource = [self->_dataSource2 mutableCopy];
                    
                    break;
                    
                default:
                    break;
            }
            int tabviewTag = self->_currentPage % 2;
            UITableView *reuseTableView = self->_scrollTableViews[tabviewTag];
            [reuseTableView reloadData];
            [self.myTableView1.mj_header endRefreshing];
            [self.myTableView2.mj_header endRefreshing];
            self.myTableView1.scrollEnabled = YES;
            self.myTableView2.scrollEnabled = YES;
        });
    } failure:^(NSError *error) {
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
    }];
}

-(void)loadMoreData{
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    NSString *str =[NSString stringWithFormat:@"ordergetNotAcceptOrder"];
    _pageNo1++;
    _pageNo2++;
    
    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo1] forKey:@"page"];
            
            break;
        case 1:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo2] forKey:@"page"];
            break;
       
        default:
            break;
    }

    
    [dic setValue:@10 forKey:@"size"];
    
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    
      
    [self.temdataSource removeAllObjects];

    self.myTableView1.scrollEnabled = NO;
    self.myTableView2.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
    });
    [NetWorking startPOSTRequestWithUrl:str parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        NSArray *arr = [data objectForKey:@"data"];
        switch (self->_currentPage) {
            case 0:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        pingtairenwuModel * model = [pingtairenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource1 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource1 mutableCopy];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.scrollEnabled = YES;
                        self.myTableView2.scrollEnabled = YES;
                    });
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.scrollEnabled = YES;
                        self.myTableView2.scrollEnabled = YES;
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                NSLog(@"_dataSource1==%lu",(unsigned long)self->_dataSource1.count);
                NSLog(@"_dataSource2==%lu",(unsigned long)self->_dataSource2.count);

                
                break;
            case 1:
                //已接单
                NSLog(@"_dataSource2==%lu",(unsigned long)self->_dataSource2.count);
                NSLog(@"_dataSource1==%lu",(unsigned long)self->_dataSource1.count);
                
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        pingtairenwuModel * model = [pingtairenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource2 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource2 mutableCopy];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.scrollEnabled = YES;
                        self.myTableView2.scrollEnabled = YES;
                        
                    });
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.scrollEnabled = YES;
                        self.myTableView2.scrollEnabled = YES;
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                
                break;
        
            default:
                break;
        }
       
        
     
    } failure:^(NSError *error) {
        
    }];
}
-(void)changeData{
    
    switch (_currentPage) {
        case 0:
            //已接单
            if (!_dataSource1.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            break;
        case 1:
            //已接单
            if (_dataSource2.count==0||!_dataSource2) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            break;
      
        default:
            break;
    }
    
}
-(void)changeSouce{
//    _myImageView.hidden = YES;
    
    switch (_currentPage) {
        case 0:
            //已接单
            self->_dataSource = [self->_dataSource1 mutableCopy];
            
            break;
        case 1:
            //已接单
            self->_dataSource = [self->_dataSource2 mutableCopy];;
            
            break;
        default:
            break;
    }
    [self.myTableView1 reloadData];
    [self.myTableView2 reloadData];
    [self.myTableView1.mj_header endRefreshing];
    [self.myTableView2.mj_header endRefreshing];
}
#pragma mark --rightBtn--
-(void)creatNavRightBtn{
    UIBarButtonItem *pulishButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
    [pulishButton setTintColor:[UIColor whiteColor]];
    
//    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]initWithTitle:@"titi" style:UITabBarSystemItemContacts target:self action:@selector(save:)];
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:pulishButton,nil]];
}
-(void)search{
    searchController * vc = [searchController new];
    vc.currentPage = 6;
    vc.sum = _sum;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 实例化ScrollView
-(void) initScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height - TOPHEIGHT)];
    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width * _tabCount, 0);
    _scrollView.backgroundColor = baseBackgroundColor;
    
    self.scrollView.alwaysBounceVertical = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
}

#pragma mark -- 实例化顶部的tab
-(void) initTopTabs{
    
    if (!_btnNameArr) {
        _btnNameArr = [[NSMutableArray alloc]initWithCapacity:_tabCount];
    }
    
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _topMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView.showsHorizontalScrollIndicator = NO;
    
    _topScrollView.showsVerticalScrollIndicator = YES;
    
    _topScrollView.bounces = NO;
    
    _topScrollView.delegate = self;
    
    if (_tabCount >= 6) {
        _topScrollView.contentSize = CGSizeMake(width * _tabCount, TOPHEIGHT);
        
    } else {
        _topScrollView.contentSize = CGSizeMake(_mViewFrame.size.width, TOPHEIGHT);
    }
    
    
    [self.view addSubview:_topMainView];
    
    [_topMainView addSubview:_topScrollView];
    
    
    
    for (int i = 0; i < _btnNameArr.count; i ++) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(i * width, 0, width, TOPHEIGHT)];
        
        view.backgroundColor = [UIColor whiteColor];
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, TOPHEIGHT)];
        button.tag = i;
        [button setTitle:[NSString stringWithFormat:@"%@", _btnNameArr[i]] forState:UIControlStateNormal];
        [button setTitleColor:basetextColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(tabButton:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = textfont;
        [view addSubview:button];
        
        UIView *vview = [[UIView alloc] initWithFrame:CGRectMake(width-1,ZTmargin*2, 1,TOPHEIGHT-ZTmargin*4)];
        [button addSubview:vview];
        vview.backgroundColor = ZXColor(208, 208, 208);
        
        [_topViews addObject:view];
        [_topScrollView addSubview:view];
    }
}
#pragma mark --点击顶部的按钮所触发的方法
-(void) tabButton: (UIButton*) sender{
    UIButton *button = sender;
    [_scrollView setContentOffset:CGPointMake(button.tag * _mViewFrame.size.width, 0) animated:YES];
    
    
}

#pragma mark --初始化下方的TableViews
-(void) initDownTables{
    for (int i = 0; i < 2; i ++) {
        UITableView * myTableView = [[UITableView alloc] initWithFrame:CGRectMake(i * _mViewFrame.size.width, ZTmargin + TOPHEIGHT, _mViewFrame.size.width, ScreenHeight - TOPHEIGHT-49-ZTmargin-64)];
        myTableView.backgroundColor = baseBackgroundColor;
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.tag = i;
        switch (i) {
            case 0:
                _myTableView1 = myTableView;
                break;
            case 1:
                _myTableView2 = myTableView;
                break;
            default:
                break;
        }
        myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_scrollTableViews addObject:myTableView];
        [_scrollView addSubview:myTableView];
    }
}
-(void)refersh{
    _pageNo1 =_pageNo2  = 1;
    _myTableView1.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        [self loadData];
    }];
    _myTableView2.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        [self loadData];
    }];
    _myTableView1.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    _myTableView2.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}
#pragma mark -- 初始化滑动的指示View
-(void) initSlideView{
    
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _slideView = [[UIView alloc] initWithFrame:CGRectMake(0, TOPHEIGHT - 1, width, 1)];
    [_slideView setBackgroundColor:titleBlueColor];
    [_topScrollView addSubview:_slideView];
}

#pragma mark --根据scrollView的滚动位置复用tableView，减少内存开支
-(void) updateTableWithPageNumber: (NSUInteger) pageNumber{
    [self changeData];
    [self changeBackColorWithPage:pageNumber];
    
    int tabviewTag = pageNumber % 2;
    
    CGRect tableNewFrame = CGRectMake(pageNumber * _mViewFrame.size.width, TOPHEIGHT, _mViewFrame.size.width, ScreenHeight - 64 - 49 - ZTmargin - TOPHEIGHT);
    
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    reuseTableView.frame = tableNewFrame;
    [reuseTableView reloadData];
}


- (void) changeBackColorWithPage: (NSInteger) currentPage {
    for (int i = 0; i < _btnNameArr.count; i ++) {
        UIView *tempView = _topViews[i];
        UIButton *button = [tempView subviews][0];
        if (i == currentPage) {
            tempView.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:titleBlueColor forState:UIControlStateNormal];
        } else {
            tempView.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:baseGlayColor forState:UIControlStateNormal];
        }
    }
    [self.view setNeedsLayout];
}


#pragma mark -- scrollView的代理方法

-(void) modifyTopScrollViewPositiong: (UIScrollView *) scrollView{
    if ([_topScrollView isEqual:scrollView]) {
        CGFloat contentOffsetX = _topScrollView.contentOffset.x;
        
        CGFloat width = _slideView.frame.size.width;
        
        int count = (int)contentOffsetX/(int)width;
        
        CGFloat step = (int)contentOffsetX%(int)width;
        
        CGFloat sumStep = width * count;
        
        if (step > width/2) {
            
            sumStep = width * (count + 1);
            
        }
        
        [_topScrollView setContentOffset:CGPointMake(sumStep, 0) animated:YES];
        
        
        return;
    }
    
}

///拖拽后调用的方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //[self modifyTopScrollViewPositiong:scrollView];
}



-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollViewDidEndDecelerating:scrollView];
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{
    if ([scrollView isEqual:_scrollView]) {
        _currentPage = _scrollView.contentOffset.x/_mViewFrame.size.width;
        
        [self updateTableWithPageNumber:_currentPage];
        NSLog(@"scrollView的页数=%ld",(long)_currentPage);
        
        [self changeBackColorWithPage:_currentPage];
        
        return;
    }
    [self modifyTopScrollViewPositiong:scrollView];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([_scrollView isEqual:scrollView]) {
        CGRect frame = _slideView.frame;
        
        if (self.tabCount <= 6) {
            frame.origin.x = scrollView.contentOffset.x/_tabCount;
        } else {
            frame.origin.x = scrollView.contentOffset.x/6;
        }
        _slideView.frame = frame;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
